package com.shuwen.gcdj.common.util;

import cn.hutool.core.collection.CollectionUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class FrpStringUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(com.shuwen.gcdj.common.util.FrpStringUtil.class);

    private static final String NUMBER_REGEX = "[^(0-9)]";


    private FrpStringUtil() {
    }

    /**
     * 如果传入的是null，返回空字符串，如果不是null，返回对象的字符串类型
     *
     * @param object object
     */
    public static String changeNullToBlank(Object object) {
        if (null == object) {
            return "";
        }
        return object.toString();


    }

    /**
     * 获取字符串列表中最大的字符串
     *
     * @param strings strings
     */
    public static String maxString(Collection<String> strings) {
        if (CollectionUtil.isEmpty(strings)) {//如果传的集合为空，返回null
            return null;
        }
        Iterator<String> it = strings.iterator();
        String maxString = it.next();
        while (it.hasNext()) {
            String temp = it.next();
            if (temp.compareTo(maxString) > 0) {
                maxString = temp;
            }
        }
        if ("".equals(maxString)) {
            return null;
        }
        return maxString;
    }

    /**
     * 从两个字符串中获取较大的那个
     *
     * @param a
     * @param b
     */
    public static String maxString(String a, String b) {
        String result = null;
        if (a != null && b == null) {
            result = a;
        } else if (a == null && b != null) {
            result = b;
        } else if (a != null && a.compareTo(b) >= 0) {
            result = a;
        } else {
            result = b;
        }
        return result;
    }

    /**
     * 从字符串列表中获取最小的字符串
     *
     * @param strings strings
     */
    public static String minString(Collection<String> strings) {
        if (CollectionUtil.isEmpty(strings)) {//如果传的集合为空，返回null
            return null;
        }
        Iterator<String> it = strings.iterator();
        String minString = it.next();
        while (it.hasNext()) {
            String temp = it.next();
            if (temp.compareTo(minString) < 0) {
                minString = temp;
            }
        }
        if ("".equals(minString)) {
            return null;
        }
        return minString;
    }

    /**
     * 从两个字符串中获取较小的那个
     *
     * @param a
     * @param b
     */
    public static String minString(String a, String b) {
        String result = null;
        if (a != null && b == null) {
            result = a;
        } else if (a == null && b != null) {
            result = b;
        } else if (a != null && a.compareTo(b) <= 0) {
            result = a;
        } else {
            result = b;
        }
        return result;
    }

    /**
     * 把ID集合用逗号拼接起来
     *
     * @param ids ids
     */
    public static List<String> unGenerateInCondition(String ids) {
        if (StringUtils.isBlank(ids) || "''".equals(ids)) {
            return new ArrayList<>();
        }
        String[] oldList = ids.split(",");
        List<String> newList = new ArrayList<>();
        for (String id : oldList) {
            String newId = id.replace("'", "");
            newList.add(newId);
        }
        return newList;
    }

    /**
     * 把ID集合用逗号拼接起来
     *
     * @param ids ids
     */
    public static List<Integer> unGenerateIntInCondition(String ids) {
        if (StringUtils.isBlank(ids) || "''".equals(ids)) {
            return new ArrayList<>();
        }
        String[] oldList = ids.split(",");
        List<Integer> newList = new ArrayList<>();
        for (String id : oldList) {
            String newId = id.replace("'", "");
            newList.add(Integer.parseInt(newId));
        }
        return newList;
    }

    /**
     * 获取SQL中IN查询方式的sql
     *
     * @param ids    ids
     * @param params params
     */
    public static String getInSql(List<String> ids, List<Object> params) {
        if (CollectionUtil.isEmpty(ids)) {
            return " IN ('')";
        }
        StringBuilder sql = new StringBuilder();
        sql.append(" IN ( ");
        for (int i = 0; i < ids.size(); i++) {
            params.add(ids.get(i));
            if (i == 0) {
                sql.append("?");
            } else {
                sql.append(",?");
            }
        }
        sql.append(" ) ");
        return sql.toString();
    }

    /**
     * 获取SQL中IN查询方式的sql
     *
     * @param ids    ids
     * @param params params
     */
    public static String getInSql(Collection<String> ids, List<Object> params) {
        List<String> newIds = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(ids)) {
            newIds.addAll(ids);
        }
        return getInSql(newIds, params);
    }

    /**
     * 获取SQL中IN查询方式的sql
     *
     * @param idstr  idstr
     * @param params params
     */
    public static String getInSql(String idstr, List<Object> params) {
        List<String> ids = unGenerateInCondition(idstr);
        return getInSql(ids, params);
    }

    /**
     * 过滤客户名称
     *
     * @param customName customName
     * @return <p>@author xuqm</p>
     * <p>@date 2018年7月13日</p>
     */
    public static String customNameFilter(String customName) {
        if (StringUtils.isBlank(customName)) {
            return customName;
        }
        String newCustomName = customName;
        newCustomName = newCustomName.replace('(', '（').replace(')', '）');
        return newCustomName.trim();
    }

    /**
     * 获取对象转换的字符串
     *
     * @param obj obj
     */
    public static String getString(Object obj) {
        if (obj == null || "null".equals(obj.toString())) {
            return null;
        }
        return obj.toString();
    }

    /**
     * 对以字符串列表形式表示的数字集合求和
     *
     * @param numbers numbers
     */
    public static int sumInt(Collection<String> numbers) {
        if (CollectionUtil.isEmpty(numbers)) {
            return 0;
        }
        int sum = 0;
        for (String number : numbers) {
            if (StringUtils.isBlank(number)) {
                continue;
            }
            int num = Integer.parseInt(number);
            sum += num;
        }
        return sum;
    }

    /**
     * 把多余的html标签去掉
     *
     * @param content content
     */
    public static String replaceStringWithNotTag(String content) {
        String newContent = "";
        if (StringUtils.isBlank(content)) {
            return newContent;
        }
        newContent = StringUtils.replace(content, "<p>", "");
        newContent = StringUtils.replace(newContent, "</p>", "");
        return newContent;
    }

    /**
     * 把空字符串转换为null
     *
     * @param str str
     */
    public static String emptyToNull(String str) {
        return "".equals(str) ? null : str;
    }

    /**
     * 合同/订单模板内容过滤
     *
     * @param content content
     */
    public static String filterModelContent(String content) {
        if (StringUtils.isBlank(content)) {
            return content;
        }
        String newContent = content;
        newContent = newContent.replace("&nbsp", "&#160");
        newContent = newContent.replace("null", "");
        return newContent;
    }

    /**
     * 处理html中的br
     *
     * @param content content
     */
    public static String dealBr(String content) {
        if (StringUtils.isBlank(content)) {
            return content;
        }
        String newContent = content;
        if (StringUtils.contains(content, "</br>")) {
            newContent = content.replace("</br>", "");
        }
        if (StringUtils.contains(content, "<br>")) {
            newContent = content.replace("<br>", "<br></br>");
        }
        return newContent;
    }

    /**
     * 把字符串变为整数
     *
     * @param str str
     */
    public static int str2Int(String str, int defaultValue) {
        if (StringUtils.isBlank(str)) {
            return defaultValue;
        }
        double d = defaultValue;
        try {
            d = Double.parseDouble(str);
        } catch (Exception e) {
            LOGGER.error("str2Int exception:", e);
        }
        return (int) d;
    }

    /**
     * 把\n变成<br/>
     *
     * @param content content
     */
    public static String nToBr(String content) {
        if (StringUtils.isBlank(content)) {
            return content;
        }
        return content.replace("\n", "<br/>");
    }

    /**
     * 中文转unicode
     *
     * @param cn cn
     */
    public static String cnToUnicode(String cn) {
        char[] chars = cn.toCharArray();
        StringBuilder returnStr = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            returnStr.append("\\u" + Integer.toString(chars[i], 16));
        }
        return returnStr.toString();
    }

    public static List<String> splitStr(String str, String reg) {
        if (StringUtils.isBlank(str) || StringUtils.isBlank(reg)) {
            return new ArrayList<>();
        }
        return Arrays.asList(str.split(reg));
    }

    /**
     * 从字符串数组中随机选一个
     *
     * @param ids ids
     */
    public static String getRandom(String[] ids) {
        if (ids == null || ids.length == 0) {
            return null;
        }
        SecureRandom random = new SecureRandom();
        return ids[random.nextInt(ids.length)];
    }

    /**
     * 去除英文和中文空格
     *
     * @param str str
     */
    public static String trim(String str) {
        if (StringUtils.isBlank(str)) {
            return str;
        }
        String newStr = str.replace((char) 12288, ' ');
        return newStr.trim();
    }

    /**
     * 过滤搜索关键字
     *
     * @param key key
     */
    /*public static String filterkey(String key) {
        if (StringUtils.isBlank(key)) {
            return key;
        }
        String newKey = trim(key);
        if (StringUtils.isBlank(newKey)) {
            return newKey;
        }
        newKey = QueryParser.escape(newKey);
        return newKey;
    }*/

    /**
     * 首字母转大写
     *
     * @param s
     */
    public static String toUpperCaseFirstOne(String s) {
        if (Character.isUpperCase(s.charAt(0))) {
            return s;
        } else {
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
        }
    }

    /**
     * 首字母转小写
     *
     * @param s
     */
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0))) {
            return s;
        } else {
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
        }
    }

    /**
     * 过滤文件名
     *
     * @param fileName fileName
     */
    public static String fileNameFilter(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return fileName;
        }
        String newFileName = fileName;
        newFileName = newFileName.replace("/", "").replace("\\", "");
        return newFileName.trim();
    }

    /**
     * 导入字段过滤
     *
     * @param str str
     */
    public static String filterImportStr(String str) {
        if (StringUtils.isBlank(str)) {
            return str;
        }
        String newStr = str.trim();
        newStr = newStr.replace("<", "&lt;").replace(">", "&gt;");
        return newStr;
    }

    /**
     * 转换客户查重查询字段
     *
     * @param customName customName
     */
    public static String changeCustomSearchName(String customName) {
        if (StringUtils.isBlank(customName)) {
            return customName;
        }
        return customName.replace(" ", "").replace(" ", "").replace("(", "（").replace(")", "）").toLowerCase();
    }

    /**
     * 将map转换成url
     *
     * @param map map
     */
    public static String getUrlParamsByMap(Map<String, Object> map) {
        if (MapUtils.isEmpty(map)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append("?");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = StringUtils.substringBeforeLast(s, "&");
        }
        return s;
    }

    /**
     * 域名格式化
     *
     * @param domainName domainName
     */
    public static String domainNameFilter(String domainName) {
        if (StringUtils.isBlank(domainName)) {
            return domainName;
        }
        return domainName.trim().replace(" ", "").toLowerCase();
    }

    /**
     * 提前数字及逗号
     *
     * @param src src
     */
    public static String getNumber(String src) {
        if (StringUtils.isEmpty(src)) {
            return Strings.EMPTY;
        }
        return Pattern.compile(NUMBER_REGEX).matcher(src).replaceAll("").trim();

    }
}
